package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.DictConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.Message;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.MessageService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.EssentialInformation;
import com.ibeetl.cms.entity.HighlevelTalents;
import com.ibeetl.cms.entity.Sincerity;
import com.ibeetl.cms.entity.StateTable;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.util.common;
import com.ibeetl.cms.web.quer3.HighlevelTalentsExamineQuery;
import com.ibeetl.cms.web.query.HighlevelTalentsQuery;
import com.ibeetl.cms.web.query2.HighlevelTalentsEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * HighlevelTalents 接口
 * 高层次人才
 */
@Controller
public class HighlevelTalentsController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/highlevelTalents";


    @Autowired private HighlevelTalentsService highlevelTalentsService;

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;

    @Autowired private EnterpriseService enterpriseService;

    @Autowired
    private EssentialInformationService essentialInformationService;

    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired
    private  SincerityService sincerityService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private PretrialService pretrialService;

    @Autowired
    private DeclareLimitService declareLimitService;

    private StateTable stateTable=new StateTable();
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @ResponseBody
    public ModelAndView index(String roleName,String year) {
        ModelAndView view;
        if (roleName.equals("shenbao")) {
            view = new ModelAndView("/cms/highlevelTalents/index.html") ;
            view.addObject("search", HighlevelTalentsQuery.class.getName());
        } else if (roleName.equals("shouli")) {
            view = new ModelAndView("/cms/highlevelTalents/enterpriseindex.html");
            view.addObject("search", HighlevelTalentsEnterpriseQuery.class.getName());
        } else if (roleName.equals("chushen")) {
            view = new ModelAndView("/cms/highlevelTalents/chushenindex.html");
            view.addObject("search", HighlevelTalentsExamineQuery.class.getName());
        } else {
            view = new ModelAndView("/cms/highlevelTalents/fushenindex.html");
            view.addObject("search", HighlevelTalentsExamineQuery.class.getName());
        }

        if (roleName.equals("chushen") || roleName.equals("fushen")) {
            HighlevelTalentsQuery condtion = new HighlevelTalentsQuery();

            if(StringUtils.isEmpty(year)){
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            view.addObject("year",year);
            condtion.setYear(year);

            /**
             * 获取本年度所有有申报的公司
             */
            List<HighlevelTalents> lists = highlevelTalentsService.queryCompany(condtion);
            List<Map<String, Object>> companies = new ArrayList<>(16);

            for (HighlevelTalents highlevelTalents : lists) {
                if(highlevelTalents.getCompanyId() == null){
                    continue;
                }
                Map<String, Object> item = new HashMap<>(8);
                int waitCheckNumber = 0;
                int allCheckNumber = 0;
                if (roleName.equals("chushen")) {
                    waitCheckNumber = firstCheckNumber(Long.valueOf(highlevelTalents.getCompanyId()), "TODO",year);
                    allCheckNumber = firstCheckNumber(Long.valueOf(highlevelTalents.getCompanyId()), "ALL",year);
                }else{
                    waitCheckNumber = finalCheckNumber(Long.valueOf(highlevelTalents.getCompanyId()), "TODO",year);
                    allCheckNumber = finalCheckNumber(Long.valueOf(highlevelTalents.getCompanyId()), "ALL",year);
                }
                if(waitCheckNumber == 0){
                    continue;
                }
                item.put("companyId", highlevelTalents.getCompanyId());
                item.put("companyName", highlevelTalents.getCurrentWorkingEnterprise());
                item.put("waitCheckNumber", waitCheckNumber);
                item.put("allCheckNumber", allCheckNumber);
                companies.add(item);
            }
            view.addObject("companies", companies);

            view.addObject("roleName", roleName);
        }
        return view;
    }

    /**
     * 获得本年度已办任务
     */
    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(HighlevelTalentsQuery condtion) {
        condtion.setProcessUserId(getUserId());
        condtion.setBusinessType(BusinessTypeConstant.highlevelTalents);

        if (StringUtils.isEmpty(condtion.getYear())) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        PageQuery page = condtion.getPageQuery();
        highlevelTalentsService.queryDoneTask(page);
        return JsonResult.success(page);
    }

    /**
     * 初审获取该申报，该公司下的员工
     *
     * @param companyId
     * @return
     */
    @PostMapping(MODEL + "/employees.json")
    @Function("highlevelTalents.check")
    @ResponseBody
    public JsonResult<PageQuery> employees(String companyId,String year) {
        HighlevelTalentsQuery condtion = new HighlevelTalentsQuery();
        condtion.setCompanyId(companyId);
        if (StringUtils.isEmpty(year)) {
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year);

        List<String> ids = new ArrayList();
        ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FIRSTCHECK_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        ids.add(ProcessConstant.COMPANY_ADOPT_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        condtion.setIds(ids);
        PageQuery page = condtion.getPageQuery();
        if(ids.size()!=0)
        highlevelTalentsService.queryEmployees(page);
        return JsonResult.success(page);
    }

    /**
     * 复审获取该申报，该公司下的员工
     *
     * @param companyId
     * @return
     */
    @PostMapping(MODEL + "/fushenemployees.json")
    @Function("highlevelTalents.review")
    @ResponseBody
    public JsonResult<PageQuery> fushenemployees(String companyId,String year) {
        HighlevelTalentsQuery condtion = new HighlevelTalentsQuery();
        condtion.setCompanyId(companyId);

        if (StringUtils.isEmpty(year)) {
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year);

        List<String> ids = new ArrayList();
        ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);

        condtion.setIds(ids);
        PageQuery page = condtion.getPageQuery();
        highlevelTalentsService.queryEmployees(page);
        return JsonResult.success(page);
    }


    @GetMapping(MODEL + "/shenhe.do")
    @ResponseBody
    public ModelAndView shenhe(Integer id, String roleName,String bStateCode) {
        ModelAndView view;
        if(bStateCode.equals(ProcessConstant.TO_FIRSTCHECK) && roleName.equals("chushen")){
            view= new ModelAndView("/cms/highlevelTalents/chushenedit.html");
        }else if(bStateCode.equals(ProcessConstant.TO_FINALCHECK) && roleName.equals("fushen")  ){
            view= new ModelAndView("/cms/highlevelTalents/fushenedit.html");
        }else{
            view  = new ModelAndView("/cms/highlevelTalents/findenterpriseedit.html");
            view.addObject("look",true);
        }

        HighlevelTalents highlevelTalents = highlevelTalentsService.queryById(id);
        highlevelTalents.setRoleName(roleName);
        view.addObject("highlevelTalents", highlevelTalents);
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("highlevelTalents")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/highlevelTalents/edit.html");
        HighlevelTalents highlevelTalents = highlevelTalentsService.queryById(id);
        view.addObject("highlevelTalents", highlevelTalents);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("highlevelTalents")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/highlevelTalents/add.html");
        Long userid = getUserId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userid);
        view.addObject("essentialInformation", essentialInformation);
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("highlevelTalents")
    @ResponseBody
    public JsonResult<PageQuery> list(HighlevelTalentsQuery condtion)
    {
        Long userid = getUserId();
        condtion.setUserid(userid);
        if (StringUtils.isEmpty(condtion.getYear())) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        PageQuery page = condtion.getPageQuery();
        highlevelTalentsService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /**
     * 受理页面数据
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/Acceptancelist.json")
    @Function("highlevelTalents.company")
    @ResponseBody
    public JsonResult<PageQuery> Acceptancelist(HighlevelTalentsQuery condtion) {
        Long userid = getUserId();
        condtion.setUserid(userid);
        if (StringUtils.isEmpty(condtion.getYear())) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        PageQuery page = condtion.getPageQuery();

        condtion.setCompanyId(userid.toString());
        if(condtion.getBusinessState()=="" || condtion.getBusinessState()==null){
            condtion.setBusinessState(ProcessConstant.TO_COMPANY);
        }else {
            condtion.setBusinessState(condtion.getBusinessState());
        }
        //查询企业数据
        highlevelTalentsService.findenterprise(page);
        return JsonResult.success(page);
    }
    @Autowired
    private DictConsoleService dictConsoleService;
    /**
     * 新增（保存）（保存并申请）
     *
     * @param highlevelTalents
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("highlevelTalents")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)HighlevelTalents highlevelTalents,String judge)
    {
        Long userId = getUserId();
        String yearStr = dictConsoleService.getDeclareYear();
        highlevelTalents.setYear(yearStr);
        highlevelTalents.setUserId(userId.intValue());
        highlevelTalents.setCompanyId(Math.toIntExact(platformService.getCurrentUser().getCompanyId()));

        common.common(stateTable,judge);
        highlevelTalents.setCreationDate(new Date());
        highlevelTalents.setDateReporting(stateTable.getDate());
        highlevelTalents.setBusinessState(stateTable.getBusinessState());
        highlevelTalents.setBusinessStateCode(stateTable.getBusinessStateCode());

        highlevelTalentsService.save(highlevelTalents);
        //调用增加业务流程数据
        businessProcessService.processInformation(highlevelTalents.getId(),stateTable.getBusinessState(),
                stateTable.getBusinessStateCode(),highlevelTalents.getHandlingSuggestion(),"成功"
                , BusinessTypeConstant.highlevelTalents);
        return new JsonResult().success();
    }
    /**
     * 编辑（保存）（保存并申请）
     *
     * @param highlevelTalents
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("highlevelTalents")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  HighlevelTalents highlevelTalents,String judge) {
        common.common(stateTable,judge);
        highlevelTalents.setDateReporting(stateTable.getDate());
        highlevelTalents.setBusinessState(stateTable.getBusinessState());
        highlevelTalents.setBusinessStateCode(stateTable.getBusinessStateCode());
        boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }



    @GetMapping(MODEL + "/view.json")
    @Function("highlevelTalents")
    @ResponseBody
    public JsonResult<HighlevelTalents>queryInfo(Integer id) {
        HighlevelTalents highlevelTalents = highlevelTalentsService.queryById( id);
        return  JsonResult.success(highlevelTalents);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("highlevelTalents")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        highlevelTalentsService.batchDelHighlevelTalents(idList);
        return new JsonResult().success();
    }
    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/highlevelTalents/findenterpriseedit.html");
        HighlevelTalents highlevelTalents = highlevelTalentsService.queryById(id);
        view.addObject("look",true);
        view.addObject("highlevelTalents", highlevelTalents);
        return view;
    }



    /**
     * 单位产业人才点击受理页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/acceptance.do")
    @Function("highlevelTalents.company")
    @ResponseBody
    public ModelAndView acceptance(Integer id) {
        ModelAndView view = new ModelAndView("/cms/highlevelTalents/acceptance.html");
        HighlevelTalents highlevelTalents = highlevelTalentsService.queryById(id);
        view.addObject("highlevelTalents", highlevelTalents);
        return view;
    }


    /**
     * 受理终止
     */
    @PostMapping(MODEL + "/Admissibility.json")
    @Function("highlevelTalents.company")
    @ResponseBody
    public JsonResult<String> Admissibility(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("highlevel_talents"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }

        highlevelTalents.setBusinessState(ProcessConstant.TERMINIATE_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.TERMINIATE);
        highlevelTalents.setProcessResult(ProcessConstant.COMPANY_TERMINIATE_STR);

        boolean postResult = pretrialService.post(AppInterfaceType.HIGHLEVEL_TALENTS_TYPE, highlevelTalents.getExternalTaskId(), "2", "", "", highlevelTalents.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(highlevelTalents.getId(), highlevelTalents.getBusinessState(),
                        highlevelTalents.getBusinessStateCode(), highlevelTalents.getHandlingSuggestion(), ProcessConstant.COMPANY_TERMINIATE_STR, BusinessTypeConstant.highlevelTalents);

                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }

    }

    /**
     * 初审终止
     */
    @PostMapping(MODEL + "/FirstTrialTermination.json")
    @Function("highlevelTalents.check")
    @ResponseBody
    public JsonResult<String> FirstTrialTermination(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        highlevelTalents.setBusinessState(ProcessConstant.TERMINIATE_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.TERMINIATE);
        highlevelTalents.setProcessResult(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        highlevelTalents.setProcessUserId(currentUser.getId().intValue());
        highlevelTalents.setProcessUserName(currentUser.getName());
        boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(highlevelTalents.getId(),highlevelTalents.getBusinessState(),
                    highlevelTalents.getBusinessStateCode(),highlevelTalents.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_TERMINIATE_STR,BusinessTypeConstant.highlevelTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }

    }

    /**
     * 复审终止
     */
    @PostMapping(MODEL + "/RetrialTermination.json")
    @Function("highlevelTalents.review")
    @ResponseBody
    public JsonResult<String> RetrialTermination(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        highlevelTalents.setBusinessState(ProcessConstant.TERMINIATE_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.TERMINIATE);
        highlevelTalents.setProcessResult(ProcessConstant.FINALCHECK_TERMINIATE_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        highlevelTalents.setReviewUserId(currentUser.getId().intValue());
        highlevelTalents.setReviewUserName(currentUser.getName());
        boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(highlevelTalents.getId(),highlevelTalents.getBusinessState(),
                    highlevelTalents.getBusinessStateCode(),highlevelTalents.getHandlingSuggestion(),ProcessConstant.FINALCHECK_TERMINIATE_STR,BusinessTypeConstant.highlevelTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 受理退回
     */
    @PostMapping(MODEL + "/AdmissibleReturn.json")
    @Function("highlevelTalents.company")
    @ResponseBody
    public JsonResult<String> AdmissibleReturn(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("highlevel_talents"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        highlevelTalents.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        highlevelTalents.setProcessResult(ProcessConstant.COMPANY_BACK_STR);
        boolean postResult = pretrialService.post(AppInterfaceType.HIGHLEVEL_TALENTS_TYPE, highlevelTalents.getExternalTaskId(), "1", "", "", highlevelTalents.getHandlingSuggestion(), "1");

        if (postResult) {
            boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(highlevelTalents.getId(), ProcessConstant.COMPANY_BACK_STR,
                        ProcessConstant.COMPANY_BACK, highlevelTalents.getHandlingSuggestion(), ProcessConstant.COMPANY_BACK_STR, BusinessTypeConstant.highlevelTalents);
                //给企业发一条退回信息
                Message message = new Message();
                message.setCompanyId(highlevelTalents.getCompanyId());
                message.setUserId(highlevelTalents.getUserId());
                message.setStatus(-1);
                message.setContent(highlevelTalents.getHandlingSuggestion());
                message.setType(Integer.parseInt(BusinessTypeConstant.highlevelTalents));
                message.setCreateDate(new Date());
                messageService.save(message);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }


    }

    /**
     * 初审退回
     */
    @PostMapping(MODEL + "/initialReview.json")
    @Function("highlevelTalents.check")
    @ResponseBody
    public JsonResult<String> initialReview(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        highlevelTalents.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        highlevelTalents.setProcessResult(ProcessConstant.FIRSTCHECK_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        highlevelTalents.setProcessUserId(currentUser.getId().intValue());
        highlevelTalents.setProcessUserName(currentUser.getName());
        boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(highlevelTalents.getId(),ProcessConstant.FIRSTCHECK_STR,
                    ProcessConstant.FIRSTCHECK,highlevelTalents.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_STR,BusinessTypeConstant.highlevelTalents);
            //给企业发一条退回信息
            Message message=new Message();
            message.setCompanyId(highlevelTalents.getCompanyId());
            message.setUserId(highlevelTalents.getUserId());
            message.setStatus(-1);
            message.setContent(highlevelTalents.getHandlingSuggestion());
            message.setType(Integer.parseInt(BusinessTypeConstant.highlevelTalents));
            message.setCreateDate(new Date());
            messageService.save(message);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审退回
     */
    @PostMapping(MODEL + "/Reexamination.json")
    @Function("highlevelTalents.review")
    @ResponseBody
    public JsonResult<String> Reexamination(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        highlevelTalents.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        highlevelTalents.setProcessResult(ProcessConstant.FINALCHECK_BACK_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        highlevelTalents.setReviewUserId(currentUser.getId().intValue());
        highlevelTalents.setReviewUserName(currentUser.getName());
        boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(highlevelTalents.getId(),ProcessConstant.FINALCHECK_BACK_STR,
                    ProcessConstant.FINALCHECK_BACK,highlevelTalents.getHandlingSuggestion(),ProcessConstant.FINALCHECK_BACK_STR,BusinessTypeConstant.highlevelTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 受理通过
     */
    @PostMapping(MODEL + "/AcceptanceOK.json")
    @Function("highlevelTalents.company")
    @ResponseBody
    public JsonResult<String> AcceptanceOK(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("highlevel_talents"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        highlevelTalents.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        highlevelTalents.setProcessResult(ProcessConstant.COMPANY_ADOPT_STR);
        highlevelTalents.setCompanyDeclareTime(new Date());
        boolean postResult = pretrialService.post(AppInterfaceType.HIGHLEVEL_TALENTS_TYPE, highlevelTalents.getExternalTaskId(), "0", highlevelTalents.getSubsidyAmount().toString(), "元", highlevelTalents.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(highlevelTalents.getId(), ProcessConstant.COMPANY_ADOPT_STR,
                        ProcessConstant.COMPANY_ADOPT, highlevelTalents.getHandlingSuggestion(), ProcessConstant.COMPANY_ADOPT_STR, BusinessTypeConstant.highlevelTalents);

                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }

    }

    /**
     *  初审通过
     */
    @PostMapping(MODEL + "/FirstTrial.json")
    @Function("highlevelTalents.check")
    @ResponseBody
    public JsonResult<String> FirstTrial(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        String businessType = "9";
        List<Sincerity> sincerityList = sincerityService.blacklist(highlevelTalents.getUserId(), highlevelTalents.getCompanyId(), businessType);
        if (null != sincerityList && sincerityList.size() > 0) {
            //用户或用户所属企业已进入黑名单
            for (Sincerity sincerity : sincerityList) {
                if (sincerity.getType().equals(Long.toString(RoleConstant.PERSON))) {
                    //个人
                    return JsonResult.failMessage(highlevelTalents.getName() + "在黑名单中有记录");
                } else if (sincerity.getType().equals(Long.toString(RoleConstant.COMPANY))) {
                    //企业
                    String name = enterpriseService.findenterprise(highlevelTalents.getCompanyId()).getEnterpriseName();
                    return JsonResult.failMessage(name + "公司在黑名单中有记录");
                }
            }
        }

        highlevelTalents.setBusinessState(ProcessConstant.TO_FINALCHECK_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.TO_FINALCHECK);
        highlevelTalents.setProcessResult(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        highlevelTalents.setProcessUserId(currentUser.getId().intValue());
        highlevelTalents.setProcessUserName(currentUser.getName());
        boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(highlevelTalents.getId(),ProcessConstant.FIRSTCHECK_ADOPT_STR,
                    ProcessConstant.FIRSTCHECK_ADOPT,highlevelTalents.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_ADOPT_STR,BusinessTypeConstant.highlevelTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审通过
     */
    @PostMapping(MODEL + "/ReviewThrough.json")
    @Function("highlevelTalents.review")
    @ResponseBody
    public JsonResult<String> ReviewThrough(@Validated(ValidateConfig.UPDATE.class) HighlevelTalents highlevelTalents) {
        highlevelTalents.setBusinessState(ProcessConstant.DONE_STR);
        highlevelTalents.setBusinessStateCode(ProcessConstant.DONE);
        highlevelTalents.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
    //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        highlevelTalents.setReviewUserId(currentUser.getId().intValue());
        highlevelTalents.setReviewUserName(currentUser.getName());
        boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(highlevelTalents.getId(),ProcessConstant.FINALCHECK_ADOPT_STR,
                    ProcessConstant.FINALCHECK_ADOPT,highlevelTalents.getHandlingSuggestion(),ProcessConstant.FINALCHECK_ADOPT_STR,BusinessTypeConstant.highlevelTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


    @PostMapping(MODEL + "/batchFinalCheckPass.json")
    @Function("highlevelTalents.review")
    @ResponseBody
    public JsonResult<String> batchFinalCheckPass(String ids,String year) {
        /**
         * 更改状态为生效
         */
        List<Long> idList = ConvertUtil.str2longs(ids);
        for(Long id : idList){
            /**
             * 获得这个公司id下所有待复审的业务
             */
            HighlevelTalentsQuery condtion = new HighlevelTalentsQuery();
            condtion.setCompanyId(String.valueOf(id));
            if(StringUtils.isEmpty(year)){
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            condtion.setYear(year);

            List<String> params = new ArrayList();
            params.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            condtion.setIds(params);
            PageQuery page = condtion.getPageQuery();
            page.setPageSize(Integer.MAX_VALUE);
            highlevelTalentsService.queryEmployees(page);
            List<HighlevelTalents> highlevelTalentsList = page.getList();

            for(HighlevelTalents highlevelTalents : highlevelTalentsList){
                highlevelTalents.setBusinessState(ProcessConstant.DONE_STR);
                highlevelTalents.setBusinessStateCode(ProcessConstant.DONE);
                highlevelTalents.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
                //复审人和id
                CoreUser currentUser = platformService.getCurrentUser();
                highlevelTalents.setReviewUserId(currentUser.getId().intValue());
                highlevelTalents.setReviewUserName(currentUser.getName());
                boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
                if (success) {
                    //调用增加业务流程数据
                    businessProcessService.processInformation(highlevelTalents.getId(),ProcessConstant.FINALCHECK_ADOPT_STR,
                            ProcessConstant.FINALCHECK_ADOPT,highlevelTalents.getHandlingSuggestion(),ProcessConstant.FINALCHECK_ADOPT_STR,BusinessTypeConstant.highlevelTalents);
                } else {
                    return JsonResult.failMessage("保存失败");
                }
            }
        }
        return JsonResult.success();
    }

// 人才公共方法(所有)

    /**
     * 公共方法
     * 用于获取登录ID
     *
     * @return
     */
    public Long getUserId() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        return userId;
    }

    /**
     * 获取初审的数量
     */
    private int firstCheckNumber(Long companyId, String type,String year) {
        /**
         * 获取待初审的数量,type = 'TODO'
         */

        HighlevelTalentsQuery condition = new HighlevelTalentsQuery();
        condition.setCompanyId(String.valueOf(companyId));
        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year);

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
            ids.add(ProcessConstant.COMPANY_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        } else {
            ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FIRSTCHECK_STR);
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            ids.add(ProcessConstant.COMPANY_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        }

        condition.setIds(ids);
        int size = highlevelTalentsService.queryEmployeesCount(condition);
        return size;
    }

    /**
     * 获取复审的数量
     */
    private int finalCheckNumber(Long companyId, String type,String year) {
        /**
         * 获取待初审的数量,type = 'TODO'
         */

        HighlevelTalentsQuery condition = new HighlevelTalentsQuery();
        condition.setCompanyId(String.valueOf(companyId));
        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year);

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        } else {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);

            ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
            ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
        }

        condition.setIds(ids);
        int size = highlevelTalentsService.queryEmployeesCount(condition);
        return size;
    }
}
